package ops

import (
	"time"

	"github.com/sirupsen/logrus"
)

// Stat 统计
type Stat struct {
	total       int64
	circle      int64
	circleCount int64
	circleStart time.Time
}

// NewStat 新建统计
func NewStat(circle int64) *Stat {
	return &Stat{
		circle:      circle,
		circleStart: time.Now(),
	}
}

// Dump 打印统计
func (s *Stat) Dump() {
	s.circleCount++
	if s.circleCount%s.circle != 0 {
		return
	}

	var ops int64

	endTime := time.Now()
	millis := int64(endTime.Sub(s.circleStart) / time.Millisecond)
	if millis > 0 {
		ops = s.circleCount * 1000 / millis
	}

	s.circleCount = 0
	s.circleStart = time.Now()

	logrus.WithField("total", s.total).WithField("circle", s.circle).WithField("ops", ops).Info("stat")
}
